package cn.edu.neusoft.neufooddemo.db;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Neusoft on 2017/4/6.
 */

public class RecordDBOperation {
    private String TABLE_NAME="records";
    private SQLiteDatabase db;
    public RecordDBOperation(RecordSQLiteOpenHelper helper){
        db = helper.getWritableDatabase();
    }
    /** * 插入数据 */
    public void insertData(String tempName) {
        db.execSQL("insert into "+TABLE_NAME+"(name) values('" + tempName + "')");
        db.close();
    }

    /** * 模糊查询数据 */
    public List queryData(String tempName) {
        List list=new ArrayList<>();
        Cursor cursor = db.rawQuery(
                "select id as _id,name from "+TABLE_NAME+" where name like '%" + tempName + "%' order by id desc ", null);
        while (cursor.moveToNext()) {
            Map map=new HashMap<>();
            map.put("name",cursor.getString(cursor.getColumnIndex("name")));
            list.add(map);
        }
        return list;
    }
    /** * 检查数据库中是否已经有该条记录 */
    public boolean hasData(String tempName) {
        Cursor cursor =db.rawQuery(
                "select id as _id,name from "+TABLE_NAME+" where name =?", new String[]{tempName});
        //判断是否有下一个
        return cursor.moveToNext();
    }

    /** * 清空数据 */
    public void deleteData() {
        db.execSQL("delete from "+TABLE_NAME);
        db.close();
    }
}
